import { Component, OnInit } from '@angular/core';
import { EngineModelService } from './engine-model.service';
import { PaginationModel } from 'app/widgets/pagination';
import { environment } from '../../../../environments/environment';
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js";
import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
  selector: 'app-engine-model',
  templateUrl: './engine-model.component.html',
  styleUrls: ['./engine-model.component.scss'],
  providers: [EngineModelService]
})
export class EngineModelComponent implements OnInit {
  // 分页列表post
  public getBody = {
    pageIndex: 1,
    pageSize: 10
  };
  // 分页配置
  public listPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  // 分页列表数据
  public dataList: any;
  // 列表全选
  public isCheckedAll: any = false;
  // 字典值
  public dictionaryList: any = {
    S_SCHEDULE_JOB: []
  };
  // 新增/修改body
  public editBody: any = {};
  // 新增/修改操作
  public operate: any;

  constructor(
    private engineModelService: EngineModelService
  ) { }

  ngOnInit() {
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    this.list();
  }

  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.dataList, [colName], ["asc"]);
    if (JSON.stringify(this.dataList) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.dataList, [colName], ["desc"]);
    }
    this.dataList = listDataAsc;
  }
  // 分页列表
  list(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    // this.getBody.sFundCode = _.trim(this.getBody.sFundCode);
    // this.getBody.sFundName = _.trim(this.getBody.sFundName);
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.engineModelService.list(this.getBody).subscribe(data => {
      if (data) {
        that.dataList = data.list;
        that.listPageInfo.currentPageNum = data.pageNum;
        that.listPageInfo.totalPages = data.pages;
        that.listPageInfo.total = data.total;
        that.listPageInfo.startRow = data.startRow;
        that.listPageInfo.endRow = data.endRow;
      }
    });
  }
  //个数分页
  listPageSizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.list();
    }
  }
  // 条数分页
  listPageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.list(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      _.forEach(this.dataList, item => {
        item.isChecked = true;
      });
    } else {
      _.forEach(this.dataList, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.dataList, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.dataList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 新增/修改modal,operate为操作状态
  showModel(operate) {
    let that = this;
    let checkedItem = [];
    this.operate = operate;
    _.forEach(this.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(_.cloneDeep(item));
      }
    });
    switch (operate) {
      case 'add':
        that.editBody = {};
        // 任务状态默认为0
        that.editBody.jobStatus = 0;
        window["$"]("#editModel").modal("show");
        break;
      case 'edit':
        if (checkedItem.length == 1) {
          that.editBody = checkedItem[0];
          console.info(that.editBody);
          window["$"]("#editModel").modal("show");
        } else {
          window['swal']("提示", "请选择一条数据进行操作", "warning");
        }
        break;
    }
  }
  // 字典值赋值
  getDictKey(dictKey) {
    let that = this;
    if (dictKey == '') {
      this.editBody.targetObject = '';
      this.editBody.targetMethod = '';
      this.editBody.isSpringBean = '';
    } else {
      new Promise((resolve, reject) => {
        let obj = _.filter(that.dictionaryList.S_SCHEDULE_JOB, function (item: any) {
          return item.sItemKey == dictKey;
        })
        resolve(obj);
      }).then(obj => {
        // 任务类
        that.editBody.targetObject = obj[0].sExtValue1;
        // 任务方法
        that.editBody.targetMethod = obj[0].sExtValue2;
        // 实现方法
        that.editBody.isSpringBean = obj[0].sExtValue3;
        console.info(obj)
        console.info(that.editBody.targetObject)
        console.info(that.editBody.targetMethod)
        console.info(that.editBody.isSpringBean)
      })
    }
  }
  // 新增/修改保存
  save() {
    let that = this;
    console.info(this.editBody);
    switch (this.operate) {
      case 'add':
        window['swal']({
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          showLoaderOnConfirm: true,
          title: "提示",
          text: "确认新增 " + this.editBody.jobName + " 任务吗?",
          html: true
        }, function (isConfirm) {
          if (isConfirm) {
            new Promise((resolve, reject) => {
              that.engineModelService.add(that.editBody).subscribe(data => {
                if (data) {
                  window["$"]("#editModel").modal("hide");
                  window['swal']("成功", "新增成功", "success");
                  resolve(data);
                }
              })
            }).then(data => {
              that.list();
            })
          }
        })
        break;
      case 'edit':
        window['swal']({
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          showLoaderOnConfirm: true,
          title: "提示",
          text: "确认修改 " + this.editBody.jobName + " 任务吗?",
          html: true
        }, function (isConfirm) {
          if (isConfirm) {
            new Promise((resolve, reject) => {
              that.engineModelService.edit(that.editBody).subscribe(data => {
                if (data) {
                  window["$"]("#editModel").modal("hide");
                  window['swal']("成功", "修改成功", "success");
                  resolve(data);
                }
              })
            }).then(data => {
              that.list();
            })
          }
        })
        break;
    }
  }
  // 删除
  del() {
    let that = this;
    let scheduleJobList = [];
    let checkNameList = [];
    _.filter(this.dataList, function (item: any) {
      if (item.isChecked) {
        scheduleJobList.push({
          "id": item.id,
          "jobName": item.jobName,
          "jobGroup": item.jobGroup
        })
        checkNameList.push(item.jobName);
      }
    })
    let checkNameListTips = checkNameList.join(",");
    if (scheduleJobList.length > 0) {
      window['swal']({
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        title: "提示",
        text: "<div style='max-height: 200px;overflow-y: auto;overflow-x: hidden;'>" + "请确认是否删除任务：" + checkNameListTips + "</div>",
        html: true
      }, function (isConfirm) {
        if (isConfirm) {
          let putBody: any = {
            "scheduleJobList": scheduleJobList
          }
          console.info(putBody.scheduleJobList)
          new Promise((resolve, reject) => {
            that.engineModelService.del(putBody).subscribe(data => {
              if (data) {
                window['swal']("成功", "删除成功", "success");
                resolve(data);
              }
            })
          }).then(data => {
            that.list();
          })
        }
      })
    } else {
      window['swal']("提示", "请选择一个或多个任务进行删除", "warning");
    }
  }
}
